import axios from 'axios'

// 配置基础URL
const API_BASE_URL = 'http://localhost:8081'

// 创建axios实例
const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

// 学习记录API
export const recordAPI = {
  // 获取学习历史
  getLearningHistory: (userId, courseId) => api.get(`/api/records/learning/users/${userId}/courses/${courseId}`),
  
  // 获取学习统计
  getLearningStatistics: (userId, courseId) => api.get(`/api/records/statistics/users/${userId}/courses/${courseId}`),
  
  // 获取学习时长
  getLearningDuration: (userId, courseId) => api.get(`/api/records/duration/users/${userId}/courses/${courseId}`),
  
  // 记录学习活动
  recordLearningActivity: (activityData) => api.post('/api/records/activities', activityData),
  
  // 获取学习活动列表
  getLearningActivities: (userId, courseId) => api.get(`/api/records/activities/users/${userId}/courses/${courseId}`),
  
  // 获取学习轨迹
  getLearningTrajectory: (userId, courseId) => api.get(`/api/records/trajectory/users/${userId}/courses/${courseId}`),
  
  // 导出学习记录
  exportLearningRecords: (userId, courseId, format) => api.get(`/api/records/export/users/${userId}/courses/${courseId}`, {
    params: { format },
    responseType: 'blob'
  })
}

export default api
